<template>
  <div class="test-connection">
    <div class="test-container">
      <el-card class="test-card">
        <template #header>
          <div class="card-header">
            <span>测试后端连接</span>
            <el-tag type="success">实时测试</el-tag>
          </div>
        </template>

        <div class="test-content">
          <!-- 服务器状态 -->
          <div class="status-section">
            <h3>🖥️ 服务器状态</h3>
            <div class="status-grid">
              <div class="status-item">
                <span class="status-label">原后端 (8085):</span>
                <el-tag :type="status8085.type">{{ status8085.text }}</el-tag>
                <el-button size="small" @click="test8085" :loading="testing8085">
                  测试
                </el-button>
              </div>
              <div class="status-item">
                <span class="status-label">测试后端 (8086):</span>
                <el-tag :type="status8086.type">{{ status8086.text }}</el-tag>
                <el-button size="small" @click="test8086" :loading="testing8086">
                  测试
                </el-button>
              </div>
            </div>
          </div>

          <el-divider />

          <!-- 验证码测试 -->
          <div class="api-section">
            <h3>📧 验证码发送测试</h3>
            <div class="api-form">
              <el-form :model="testForm" label-width="100px">
                <el-form-item label="邮箱地址">
                  <el-input
                    v-model="testForm.email"
                    placeholder="请输入QQ邮箱"
                    style="width: 300px;"
                  />
                </el-form-item>
                <el-form-item label="测试服务器">
                  <el-radio-group v-model="testForm.server">
                    <el-radio value="8085">原后端 (8085)</el-radio>
                    <el-radio value="8086">测试后端 (8086)</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="testSendCode" :loading="sendingCode">
                    发送验证码
                  </el-button>
                  <el-button @click="fillTestEmail">填充测试邮箱</el-button>
                </el-form-item>
              </el-form>
            </div>
            
            <div v-if="codeResult" class="result-section">
              <h4>测试结果:</h4>
              <div class="result-display">
                <el-tag :type="codeResult.success ? 'success' : 'danger'">
                  {{ codeResult.success ? '成功' : '失败' }}
                </el-tag>
                <pre class="json-display">{{ JSON.stringify(codeResult.data, null, 2) }}</pre>
              </div>
            </div>
          </div>

          <el-divider />

          <!-- 注册测试 -->
          <div class="api-section">
            <h3>👤 用户注册测试</h3>
            <div class="api-form">
              <el-form :model="registerForm" label-width="100px">
                <el-form-item label="用户名">
                  <el-input v-model="registerForm.username" placeholder="用户名" />
                </el-form-item>
                <el-form-item label="邮箱">
                  <el-input v-model="registerForm.email" placeholder="邮箱" />
                </el-form-item>
                <el-form-item label="密码">
                  <el-input v-model="registerForm.password" placeholder="密码" show-password />
                </el-form-item>
                <el-form-item label="确认密码">
                  <el-input v-model="registerForm.confirmPassword" placeholder="确认密码" show-password />
                </el-form-item>
                <el-form-item label="验证码">
                  <el-input v-model="registerForm.verificationCode" placeholder="验证码" />
                </el-form-item>
                <el-form-item label="测试服务器">
                  <el-radio-group v-model="registerForm.server">
                    <el-radio value="8085">原后端 (8085)</el-radio>
                    <el-radio value="8086">测试后端 (8086)</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item>
                  <el-button type="success" @click="testRegister" :loading="registering">
                    测试注册
                  </el-button>
                  <el-button @click="fillTestRegister">填充测试数据</el-button>
                </el-form-item>
              </el-form>
            </div>
            
            <div v-if="registerResult" class="result-section">
              <h4>注册结果:</h4>
              <div class="result-display">
                <el-tag :type="registerResult.success ? 'success' : 'danger'">
                  {{ registerResult.success ? '成功' : '失败' }}
                </el-tag>
                <pre class="json-display">{{ JSON.stringify(registerResult.data, null, 2) }}</pre>
              </div>
            </div>
          </div>

          <!-- 测试日志 -->
          <div class="logs-section">
            <h3>📋 测试日志</h3>
            <div class="logs-container">
              <div v-if="testLogs.length === 0" class="no-logs">
                暂无测试日志
              </div>
              <div v-for="(log, index) in testLogs" :key="index" class="log-item">
                <div class="log-header">
                  <span class="log-time">{{ log.time }}</span>
                  <el-tag :type="log.success ? 'success' : 'danger'" size="small">
                    {{ log.type }}
                  </el-tag>
                </div>
                <div class="log-content">
                  <p><strong>服务器:</strong> {{ log.server }}</p>
                  <p><strong>请求:</strong> {{ log.method }} {{ log.url }}</p>
                  <p><strong>响应:</strong></p>
                  <pre class="log-response">{{ JSON.stringify(log.response, null, 2) }}</pre>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'

// 响应式数据
const testing8085 = ref(false)
const testing8086 = ref(false)
const sendingCode = ref(false)
const registering = ref(false)
const codeResult = ref(null)
const registerResult = ref(null)
const testLogs = ref([])

const status8085 = reactive({
  type: 'info',
  text: '未测试'
})

const status8086 = reactive({
  type: 'info',
  text: '未测试'
})

const testForm = reactive({
  email: '',
  server: '8086'
})

const registerForm = reactive({
  username: '',
  email: '',
  password: '',
  confirmPassword: '',
  verificationCode: '',
  server: '8086'
})

// 方法
const addLog = (type, server, method, url, response, success) => {
  testLogs.value.unshift({
    time: new Date().toLocaleTimeString(),
    type,
    server,
    method,
    url,
    response,
    success
  })
  
  // 只保留最近10条日志
  if (testLogs.value.length > 10) {
    testLogs.value = testLogs.value.slice(0, 10)
  }
}

const test8085 = async () => {
  testing8085.value = true
  
  try {
    const response = await fetch('http://localhost:8085/housingHub/user/send-code', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email: 'test@qq.com' })
    })
    
    const data = await response.text()
    
    status8085.type = response.ok ? 'success' : 'warning'
    status8085.text = response.ok ? '连接正常' : `状态码: ${response.status}`
    
    addLog('连接测试', '8085端口', 'POST', '/housingHub/user/send-code', data, response.ok)
    
  } catch (error) {
    status8085.type = 'danger'
    status8085.text = '连接失败'
    
    addLog('连接测试', '8085端口', 'POST', '/housingHub/user/send-code', error.message, false)
  } finally {
    testing8085.value = false
  }
}

const test8086 = async () => {
  testing8086.value = true
  
  try {
    const response = await fetch('http://localhost:8086/housingHub/user/send-code', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email: 'test@qq.com' })
    })
    
    const data = await response.json()
    
    status8086.type = response.ok ? 'success' : 'warning'
    status8086.text = response.ok ? '连接正常' : `状态码: ${response.status}`
    
    addLog('连接测试', '8086端口', 'POST', '/housingHub/user/send-code', data, response.ok)
    
  } catch (error) {
    status8086.type = 'danger'
    status8086.text = '连接失败'
    
    addLog('连接测试', '8086端口', 'POST', '/housingHub/user/send-code', error.message, false)
  } finally {
    testing8086.value = false
  }
}

const testSendCode = async () => {
  if (!testForm.email) {
    ElMessage.warning('请输入邮箱地址')
    return
  }

  sendingCode.value = true
  codeResult.value = null

  try {
    const port = testForm.server
    const url = `http://localhost:${port}/housingHub/user/send-code`
    
    const response = await fetch(url, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email: testForm.email })
    })
    
    const data = await response.json()
    
    codeResult.value = {
      success: response.ok && data.code === '200',
      data: data
    }
    
    addLog('发送验证码', `${port}端口`, 'POST', '/housingHub/user/send-code', data, response.ok)
    
    if (response.ok && data.code === '200') {
      ElMessage.success('验证码发送成功')
      // 如果是测试服务器，自动填充验证码
      if (port === '8086' && data.data?.verificationCode) {
        registerForm.verificationCode = data.data.verificationCode.toString()
        ElMessage.info(`测试验证码已自动填充: ${data.data.verificationCode}`)
      }
    } else {
      ElMessage.error(data.message || '验证码发送失败')
    }
  } catch (error) {
    codeResult.value = {
      success: false,
      data: { error: error.message }
    }
    
    addLog('发送验证码', `${testForm.server}端口`, 'POST', '/housingHub/user/send-code', error.message, false)
    ElMessage.error('验证码发送失败: ' + error.message)
  } finally {
    sendingCode.value = false
  }
}

const testRegister = async () => {
  if (!registerForm.username || !registerForm.email || !registerForm.password || 
      !registerForm.confirmPassword || !registerForm.verificationCode) {
    ElMessage.warning('请填写完整的注册信息')
    return
  }

  registering.value = true
  registerResult.value = null

  try {
    const port = registerForm.server
    const url = `http://localhost:${port}/housingHub/user/register`
    
    const requestData = {
      username: registerForm.username,
      email: registerForm.email,
      password: registerForm.password,
      confirmPassword: registerForm.confirmPassword,
      verificationCode: registerForm.verificationCode
    }
    
    const response = await fetch(url, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(requestData)
    })
    
    const data = await response.json()
    
    registerResult.value = {
      success: response.ok && data.code === '200',
      data: data
    }
    
    addLog('用户注册', `${port}端口`, 'POST', '/housingHub/user/register', data, response.ok)
    
    if (response.ok && data.code === '200') {
      ElMessage.success('注册成功')
    } else {
      ElMessage.error(data.message || '注册失败')
    }
  } catch (error) {
    registerResult.value = {
      success: false,
      data: { error: error.message }
    }
    
    addLog('用户注册', `${registerForm.server}端口`, 'POST', '/housingHub/user/register', error.message, false)
    ElMessage.error('注册失败: ' + error.message)
  } finally {
    registering.value = false
  }
}

const fillTestEmail = () => {
  const timestamp = Date.now().toString().slice(-6)
  testForm.email = `${timestamp}@qq.com`
  ElMessage.success('测试邮箱已填充')
}

const fillTestRegister = () => {
  const timestamp = Date.now().toString().slice(-6)
  registerForm.username = `testuser${timestamp}`
  registerForm.email = testForm.email || `${timestamp}@qq.com`
  registerForm.password = 'Test123!@#'
  registerForm.confirmPassword = 'Test123!@#'
  registerForm.verificationCode = '123456'
  
  ElMessage.success('测试数据已填充')
}
</script>

<style scoped>
.test-connection {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.test-container {
  max-width: 1000px;
  margin: 0 auto;
}

.test-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 15px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  font-size: 18px;
  color: #2c3e50;
}

.test-content {
  padding: 20px 0;
}

.status-section h3,
.api-section h3,
.logs-section h3 {
  color: #409eff;
  margin-bottom: 15px;
}

.status-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 15px;
}

.status-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
}

.status-label {
  font-weight: 500;
  color: #2c3e50;
}

.api-form {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 15px;
}

.result-section h4 {
  color: #2c3e50;
  margin-bottom: 10px;
}

.result-display {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
}

.json-display {
  background: #2c3e50;
  color: #fff;
  padding: 15px;
  border-radius: 6px;
  font-size: 12px;
  max-height: 200px;
  overflow-y: auto;
  white-space: pre-wrap;
  margin-top: 10px;
}

.logs-container {
  max-height: 400px;
  overflow-y: auto;
}

.no-logs {
  text-align: center;
  color: #909399;
  padding: 40px;
  background: #f8f9fa;
  border-radius: 8px;
}

.log-item {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 15px;
}

.log-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.log-time {
  font-size: 12px;
  color: #909399;
}

.log-content p {
  margin: 5px 0;
  color: #2c3e50;
}

.log-response {
  background: #2c3e50;
  color: #fff;
  padding: 10px;
  border-radius: 4px;
  font-size: 11px;
  max-height: 150px;
  overflow-y: auto;
  white-space: pre-wrap;
}
</style>
